﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Active.Core;
using Active.Core.State;

public partial class Bill_Bill : System.Web.UI.Page
{
    private enum Views
    {
        MainView = 0,
        EditBillView = 1,
        AddOrderView = 2,
        EditOrderView = 3
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ApplyAuthorizationRules();
        }
    }

    private void ApplyAuthorizationRules()
    {
        Bill obj = GetBill();
        if (Bill.CanAddObject())
        {
            if (obj.IsNew)
            {
                this.MultiView1.ActiveViewIndex = (int)Views.EditBillView;
                this.txtStartDate.Text = DateTime.Now.ToShortDateString();
                this.lbtnReturn.Visible = false;
            }
            else
            {
                this.MultiView1.ActiveViewIndex = (int)Views.MainView;
                this.lbtnEditBill.Visible = obj.Orders.Count == 0;
                this.OrdersGridView.Columns[OrdersGridView.Columns.Count - 1].Visible =
                this.lbtnAddOrder.Visible = obj.StateValue == StateValue.CustomerEmployeeWorking;
            }
        }
        else //非客户部员工或总监
        {
            if (obj.IsNew) //非法进入
            {
                Response.Redirect("~/Bill", true);
            }
            this.MultiView1.ActiveViewIndex = (int)Views.MainView;
            this.lbtnAddOrder.Visible = false;
            this.lbtnEditBill.Visible = false;
            this.OrdersGridView.Columns[OrdersGridView.Columns.Count - 1].Visible = false;
            
        }
        this.OrdersGridView.Columns[1].Visible = MediaOrder.CanGetObject();
        
        this.btnCreateBill.Visible = obj.IsNew;
        this.btnEditBill.Visible = !obj.IsNew;
    }

    private void InitFormValue()
    {
        Bill obj = GetBill();
        txtAgentName.Text = obj.AgentName;
        txtCustomerName.Text = obj.CustomerName;
        txtStartDate.Text = obj.StartDate.Text;
        ddlProducts.DataSource = obj.Customer.Products;
        ddlProducts.DataBind();
        ddlProducts.SelectedValue = obj.ProductId.ToString();

        txtStartDate.Enabled = obj.Orders.Count == 0;
        ddlProducts.Enabled =
            txtAgentName.Enabled =
            txtCustomerName.Enabled = obj.Orders.Count == 0;
    }

    protected void txtCustomerName_TextChanged(object sender, EventArgs e)
    {
        try
        {
            Customer cust = Customer.GetCustomer(txtCustomerName.Text.Trim());
            ddlProducts.DataSource = cust.Products;
            ddlProducts.DataBind();
        }
        catch (Csla.DataPortalException ex)
        {
            ddlProducts.Items.Clear();
        }
    }

    private bool ValidateInputValue(Bill obj)
    {
        this.ErrorMessage.Text = string.Empty;
        if (!string.IsNullOrEmpty(txtAgentName.Text.Trim()))
        {
            try
            {
                Agent agent = Agent.GetAgent(txtAgentName.Text.Trim());
                obj.AgentId = agent.Id;
            }
            catch (Csla.DataPortalException ex)
            {
                ErrorMessage.Text += "请输入正确的代理名称<br />";
            }
        }
        else
        {
            obj.AgentId = 0;
        }
        if (string.IsNullOrEmpty(txtCustomerName.Text.Trim()))
        {
            ErrorMessage.Text += "请输入客户名称<br />";
        }
        else
        {
            try
            {
                Customer cust = Customer.GetCustomer(txtCustomerName.Text.Trim());
                obj.CustomerId = cust.Id;
            }
            catch (Csla.DataPortalException ex)
            {
                ErrorMessage.Text += "请输入正确的客户名称<br />";
            }
        }
        if (string.IsNullOrEmpty(ddlProducts.SelectedValue))
        {
            ErrorMessage.Text += "请选择产品<br />";
        }
        else
        {
            obj.ProductId = int.Parse(ddlProducts.SelectedValue);
        }
        if (!string.IsNullOrEmpty(ErrorMessage.Text))
        {
            return false;
        }
        return true;
    }

    protected void btnCreateBill_Click(object sender, EventArgs e)
    {
        Bill obj = GetBill();
        if (!ValidateInputValue(obj)) return;
        obj.StartDate = new Csla.SmartDate(txtStartDate.Text);
        SaveBill(obj);
        Response.Redirect(Request.RawUrl + string.Format("?id={0}", obj.Id), true);
    }

    protected void btnEditBill_Click(object sender, EventArgs e)
    {
        Bill obj = GetBill();
        if (!ValidateInputValue(obj)) return;
        obj.StartDate = new Csla.SmartDate(txtStartDate.Text);
        SaveBill(obj);
        Response.Redirect(Request.RawUrl, true);
    }

    protected void lbtnAddOrder_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = (int)Views.AddOrderView;
        CheckBoxList versions = OrderDetailsView.FindControl("PlayVersonsCheckBoxList") as CheckBoxList;
        versions.DataSource = GetBill().Product.Versions.Replace(Environment.NewLine, "|").Split('|');
        versions.DataBind();
    }

    protected void lbtnEditBill_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = (int)Views.EditBillView;
        InitFormValue();
    }

    protected void lbtnReturn_Click(object sender, EventArgs e)
    {
        OrderDetailsView.ChangeMode(DetailsViewMode.Insert);
        this.MultiView1.ActiveViewIndex = (int)Views.MainView;
    }

    #region Business Methods

    protected Bill GetBill()
    {
        string idString = Request.QueryString["id"];
        object businessObj = Session["CurrentObj"];
        if (businessObj == null || !(businessObj is Bill)
            || (!IsPostBack && !((Bill)businessObj).Id.ToString().Equals(idString)))
        {
            try
            {
                if (!string.IsNullOrEmpty(idString))
                {
                    businessObj = Bill.GetBill(int.Parse(idString));
                }
                else
                {
                    businessObj = Bill.NewBill();
                }
                Session["CurrentObj"] = businessObj;
            }
            catch (System.Security.SecurityException)
            {
                Response.Redirect("~/Bill");
            }
        }
        return businessObj as Bill;
    }

    private int SaveBill(Bill bill)
    {
        int rowsAffected = 0;
        try
        {
            Session["CurrentObj"] = bill.Save();
            rowsAffected = 1;
        }
        catch (Csla.Validation.ValidationException ex)
        {
            throw;
        }
        catch (Csla.DataPortalException ex)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw;
        }
        return rowsAffected;
    }

    #endregion

    #region BillDetailsView

    protected void BillDetailsView_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {

    }

    #endregion

    #region BillDataSource

    protected void BillDataSource_DeleteObject(object sender, Csla.Web.DeleteObjectArgs e)
    {

    }

    protected void BillDataSource_InsertObject(object sender, Csla.Web.InsertObjectArgs e)
    {
        //Bill obj = GetBill();
        //string agentName = (this.BillDetailsView.FindControl("txtAgentName") as TextBox).Text.Trim();
        //obj.AgentId = Agent.GetAgent(agentName).Id;
        //string customerName = (this.BillDetailsView.FindControl("txtCustomerName") as TextBox).Text.Trim();
        //Customer cust = Customer.GetCustomer(customerName);
        //obj.CustomerId = cust.Id;

    }

    protected void BillDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = GetBill();
    }

    protected void BillDataSource_UpdateObject(object sender, Csla.Web.UpdateObjectArgs e)
    {

    }

    #endregion

    #region OrdersDataSource

    protected void OrdersDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        e.BusinessObject = GetBill().Orders;
    }

    protected void OrdersDataSource_DeleteObject(object sender, Csla.Web.DeleteObjectArgs e)
    {
        Bill obj = GetBill();
        obj.Orders.Remove((int)e.Keys["Id"]);
        e.RowsAffected = SaveBill(obj);
        Response.Redirect(Request.RawUrl);
    }

    #endregion

    #region OrderDataSource

    protected void OrderDataSource_InsertObject(object sender, Csla.Web.InsertObjectArgs e)
    {
        Bill bill = GetBill();
        Order order = bill.Orders.AddNew();
        order.MediaId = (int)e.Values["MediaId"];
        CheckBoxList versions = OrderDetailsView.FindControl("PlayVersonsCheckBoxList") as CheckBoxList;
        order.RemovePlayVersions();
        foreach (ListItem item in versions.Items)
        {
            if (item.Selected)
            {
                order.AddPlayVersion(item.Value);
            }
        }
        order.Number = (string)e.Values["Number"];
        e.RowsAffected = SaveBill(bill);
        Response.Redirect(Request.RawUrl, true);
    }

    protected void OrderDataSource_UpdateObject(object sender, Csla.Web.UpdateObjectArgs e)
    {
        Bill bill = GetBill();
        Order order = bill.Orders.GetOrderById((int)e.Keys["Id"]);
        order.MediaId = (int)e.Values["MediaId"];
        CheckBoxList versions = dvEditOrder.FindControl("PlayVersonsCheckBoxList") as CheckBoxList;
        order.RemovePlayVersions();
        foreach (ListItem item in versions.Items)
        {
            if (item.Selected)
            {
                order.AddPlayVersion(item.Value);
            }
        }
        order.Number = (string)e.Values["Number"];
        e.RowsAffected = SaveBill(bill);
        Response.Redirect(Request.RawUrl, true);
    }

    #endregion

    //验证输入
    protected void OrderDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    {
        Label errorMessage = OrderDetailsView.FindControl("SaveOrderErrorMessage") as Label;
        errorMessage.Text = string.Empty;
        try
        {
            Media media = Media.GetMedia(e.Values["MediaName"].ToString());
            e.Values["MediaId"] = media.Id;
        }
        catch (Csla.DataPortalException ex)
        {
            errorMessage.Text += "请输入正确的媒介名称<br />";
            e.Cancel = true;
        }
    }

    //验证输入
    protected void OrderDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        Label errorMessage = OrderDetailsView.FindControl("SaveOrderErrorMessage") as Label;
        errorMessage.Text = string.Empty;
        try
        {
            Media media = Media.GetMedia(e.NewValues["MediaName"].ToString());
            e.NewValues["MediaId"] = media.Id;
        }
        catch (Csla.DataPortalException ex)
        {
            errorMessage.Text += "请输入正确的媒介名称<br />";
            e.Cancel = true;
        }
    }

    int selectedOrderId = 0;
    protected void OrdersGridView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditOrder")
        {
            selectedOrderId = Convert.ToInt32(e.CommandArgument);
            MultiView1.ActiveViewIndex = (int)Views.EditOrderView;
            CheckBoxList versions = dvEditOrder.FindControl("PlayVersonsCheckBoxList") as CheckBoxList;
            versions.DataSource = GetBill().Product.Versions.Replace(Environment.NewLine, "|").Split('|');
            versions.DataBind();

            Order order = GetBill().Orders.GetOrderById(selectedOrderId);
            foreach (ListItem item in versions.Items)
            {
                foreach (string verson in order.PlayVersions)
                {
                    if (item.Value == verson)
                    {
                        item.Selected = true;
                        break;
                    }
                }
            }
        }
    }

    protected void OrderDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
    {
        Order order = GetBill().Orders.GetOrderById(selectedOrderId);
        e.BusinessObject = order;
    }
}
